import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const foodsStore = createSlice({
  name: "foods",
  initialState: {
    //食物列表
    foodsList: [],
    //菜单激活
    activeIndex: 0,
    //添加购物车
    cartList: [],
  },
  reducers: {
    setFoodsList(state, action) {
      state.foodsList = action.payload;
    },
    changeMeanIndex(state, action) {
      state.activeIndex = action.payload;
    },
    addCart(state, action) {
      //是否添加过？以action.payload.id去cartList中匹配 匹配到了 添加过
      const item = state.cartList.find((item) => item.id === action.payload.id);
      if (item) {
        item.count++;
      } else {
        action.payload.count = 1;
        state.cartList.push(action.payload);
      }
    },
    //增加购物车中指定食物的数量
    increCount(state, action) {
      const item = state.cartList.find((item) => item.id === action.payload.id);
      item.count++;
    },
    //减少购物车中指定食物的数量
    decreCount(state, action) {
      const item = state.cartList.find((item) => item.id === action.payload.id);
      //当数量为1时，再进行减，则把该商品从购物车中删除掉
      if (item.count === 1) {
        state.cartList = state.cartList.filter((i) => {
          return i.id !== item.id;
        });
        return;
      }
      //否则进行数量减一
      item.count--;
    },
    //清空购物车
    clearCart(state) {
      state.cartList = [];
    },
  },
});

//异步获取部分
const {
  setFoodsList,
  changeMeanIndex,
  addCart,
  increCount,
  decreCount,
  clearCart,
} = foodsStore.actions;
const fetchFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get("http://localhost:3004/takeaway");
    dispatch(setFoodsList(res.data));
  };
};
export {
  fetchFoodsList,
  changeMeanIndex,
  addCart,
  increCount,
  decreCount,
  clearCart,
};

const reducer = foodsStore.reducer;
export default reducer;
